package com.yt.server.comm;

import org.apache.mina.core.session.IoSession;

import com.yt.server.AttributeStore;
import com.yt.server.Context;
import com.yt.server.api.IConnection;
import com.yt.server.api.IScope;
import com.yt.server.api.comm.ISession;

/**
 * 用户状态
 * 
 * @author 刘晶
 */
public class Session extends AttributeStore implements ISession {

	private static final long serialVersionUID = 2893666721L;

	protected long created;

	protected boolean active;// 是否活跃

	protected String clientId;// 客户端ID

	protected String sessionId;// sessionID

	protected String destinationDirectory;// 目标路径

	protected IConnection connection; // 客户端连接

	protected IScope globalScope = Context.getGlobalScope();// 大厅

	public Session() {
	}

	public Session(String sessionId) {
		this.sessionId = sessionId;
	}

	public Session(String sessionId, IoSession session) {
		super();
		this.sessionId = sessionId;
		// 建立连接
		this.connection = new Connection(session);
		// 连接和大厅关联
		this.globalScope.join(this.connection);
		this.created = connection.getCreated();
		this.clientId = connection.getClientId();
	}

	public IConnection getConnection() {
		return connection;
	}

	public long getCreated() {
		return created;
	}

	public String getSessionId() {
		return sessionId;
	}

	public void reset() {
		clientId = null;
	}

	public boolean isActive() {
		return connection.isConnected();
	}

	public void end() {
		/**
		 * 执行关闭
		 */
		active = false;
		connection.destroy();
	}

	public String getClientId() {
		return clientId;
	}

	public void setClientId(String clientId) {
		this.clientId = clientId;
	}

	public void setDestinationDirectory(String destinationDirectory) {
		this.destinationDirectory = destinationDirectory;
	}

	public String getDestinationDirectory() {
		return destinationDirectory;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((sessionId == null) ? 0 : sessionId.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Session other = (Session) obj;
		if (sessionId == null) {
			if (other.sessionId != null)
				return false;
		} else if (!sessionId.equals(other.sessionId))
			return false;
		return true;
	}
}